﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using NG; 
namespace NGDesign
{
    
    class QuestionHandler:IQuestionHandler
    {
        private string tableName = "[dbo].[Questions]";
        
        public void addQuestion(Question que)
        {
            return;
        }


        public LinkedList<Question> allQueGivenKSF(KSF ksf, string sortedBy, bool desc)
        {
            string sorted;
            if (sortedBy == string.Empty)
            {
                sorted = " {0}";
            }
            else
            {
                sorted = sortedBy;
            }
            DBConnect con = new DBConnect();
            string tbn = "[" + con.dbName + "]." + this.tableName;
           
            LinkedList<Question> queList = new LinkedList<Question>();
            if (con.OpenConnection() == false)
            {
                throw new System.Exception("Couldn't connect to the Database");
            }
            string extra = "";
            if (desc)
            {
                extra = " DESC";
            }

            string query = string.Format("SELECT * FROM {0} WHERE ksf = {1} ORDER BY " + sorted + extra,tbn,ksf.ksfCode);
            SqlCommand cmd = new SqlCommand(query, con.connection);
            SqlDataReader rdr = cmd.ExecuteReader();


            if (rdr.HasRows)
            {

                while (rdr.Read())
                {

                    Question que = new Question(int.Parse(rdr["questionNo"].ToString()),int.Parse(rdr["KSF"].ToString()),
                            rdr["questionDesc"].ToString(), bool.Parse(rdr["isObservable"].ToString()));


                    queList.AddLast(que);


                }
            }
            if (con.CloseConnection() == false)
            {
                throw new System.Exception("Couldn't disconnect from the Database");
            }
            return queList;
        }
    }
}
